package com.koi.repect.aspect;

import com.koi.common.anno.KoiRepeatSubmit;
import com.koi.common.constants.KoiCacheConstants;
import com.koi.common.ex.RepeatSubmitException;
import com.koi.common.utils.ip.IpAddressUtil;
import com.koi.common.utils.ip.IpUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.concurrent.TimeUnit;

/**
 * @author ･ᴗ･
 * @description [NoRepeatSubmitAop]
 */
@Aspect
@Component
@Order(1)
@Slf4j
public class RepeatSubmitAspect {

    @Autowired
    private RedisService redisService;

    @Value("${sa-token.token-name}")
    private String tokenName;

    @Value("${sa-token.token-prefix}")
    private String tokenPrefix;

    @Resource
    private IpAddressUtil ipAddressUtil;

    @Around(value = "@annotation(repeatSubmit)")
    public Object around(ProceedingJoinPoint joinPoint, KoiRepeatSubmit repeatSubmit) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        // 请求地址
        HttpServletRequest request = attributes.getRequest();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // System.out.println("方法名称："+signature.getMethod().getName());
        // System.out.println("方法类型："+signature.getReturnType());
        // System.out.println("参数名称："+ Arrays.toString(signature.getParameterNames()));
        // System.out.println("参数类型："+ Arrays.toString(signature.getParameterTypes()));
        // 获得客户端的IP地址
        String userIp = IpUtil.getIpAddr(request);
        // 针对某个人的话，就是用token，如果没有token就使用客户端IP进行辨别
        String authorization = request.getHeader(tokenName);
        String header = null;
        if (StringUtils.isNotBlank(authorization)) {
            header = authorization.replace(" ", "").replace(tokenPrefix, "");
        }
        // 定义redis的key
        String key = null;
        if (StringUtils.isNotBlank(header)) {
            // 这里是唯一标识，根据情况而定，里面添加用户ID或者IP地址最好，否则同一个接口一秒只能使用一次
            key = repeatSubmit.prefix() + userIp + ":[" + signature.getMethod().getName() + "-" + request.getServletPath() + "-" + header + "]";
        } else {
            // 这里是唯一标识，根据情况而定，里面添加用户ID或者IP地址最好，否则同一个接口一秒只能使用一次
            key = repeatSubmit.prefix() + userIp + ":[" + signature.getMethod().getName() + "-" + request.getServletPath() + "]";
        }
        log.info("重复提交操作电脑IP：{}", userIp);
        log.info("重复提交redis-key：{}", key);
        // 如果缓存中有这个url视为重复提交
        if (!redisService.haskey(key)) {
            // 通过，执行下一步
            Object o = joinPoint.proceed();
            // 然后存入redis并且设置1s倒计时
            redisService.setCacheObject(key, KoiCacheConstants.REPEAT_SUBMIT_KEY, repeatSubmit.value(), TimeUnit.MILLISECONDS);
            // 返回结果
            return o;
        } else {
            throw new RepeatSubmitException(500, "请勿重复提交，请稍后重试");
        }
    }

}
